package com.reader.api.thirdplatform.impl;

import com.reader.api.exception.urlauthentication.UrlAuthenticationException;
import com.reader.api.exception.urlauthentication.UrlDomainErrorException;
import com.reader.api.exception.urlauthentication.UrlEmptyException;
import com.reader.api.thirdplatform.AliUrlAuthenticationService;
import com.reader.core.utils.Md5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

/**
 * @author liujianqing
 * @date 2018/10/24
 */
public class AliUrlAuthenticationServiceImpl implements AliUrlAuthenticationService {

    @Value("${ali.urlAuthentication.privateKey}")
    private String privateKey;
    @Value("${ali.urlAuthentication.domain}")
    private String domain;
    @Value("${ali.urlAuthentication.urlKeyCode}")
    private String urlKeyCode;
    @Value("${ali.urlAuthentication.expireTime}")
    private int expireTime;

    @Override
    public String getAuthenticationUrl(String url) throws UrlAuthenticationException {

        if (StringUtils.isBlank(url)) {
            throw new UrlEmptyException();
        }

        if (!StringUtils.startsWith(url, domain)) {
            throw new UrlDomainErrorException(domain, url);
        }

        //开始鉴权
        String fileUrl = StringUtils.substringAfter(url, domain);

        long timestamp = System.currentTimeMillis() / 1000 + expireTime;

        StringBuilder timeSb = new StringBuilder()
                .append(timestamp).append("-0-0-");

        String authHash = Md5Util.encrypt(fileUrl + "-"
                + timeSb.append(privateKey).toString());

        StringBuilder retUrlSb = new StringBuilder(url)
                .append("?")
                .append(urlKeyCode).append("=")
                .append(timeSb.toString())
                .append(authHash);

        return retUrlSb.toString();
    }

}
